package com.ruoyi.voucher.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.voucher.domain.VoucherAttachment;
import com.ruoyi.voucher.domain.VoucherDetail;
import com.ruoyi.voucher.dto.VoucherDto;
import com.ruoyi.voucher.dto.VoucherReqDto;
import com.ruoyi.voucher.mapper.VoucherAttachmentMapper;
import com.ruoyi.voucher.service.IVoucherAttachmentService;
import com.ruoyi.voucher.service.impl.VoucherAttachmentServiceImpl;
import com.ruoyi.voucher.utils.FileUploadUtils;
import com.ruoyi.voucher.vo.VoucherExcelVO;
import com.ruoyi.voucher.vo.VoucherRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.voucher.domain.VoucherManage;
import com.ruoyi.voucher.service.IVoucherManageService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 凭证管理Controller
 * 
 * @author hdd
 * @date 2025-02-26
 */
@RestController
@RequestMapping("/voucherManage")
public class VoucherManageController extends BaseController
{
    @Autowired
    private IVoucherManageService voucherManageService;


    @Autowired
    private IVoucherAttachmentService voucherAttachmentService;



    /**
     * 文件上传
     */
    @Value("${upload.path}")
    private String uploadBaseDir;

    /**
     * 添加凭证时，上传文件
     * @param file
     * @param
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }

        try {
            // 保存文件到本地
            String fileName = file.getOriginalFilename();
            String attachmentUrl = FileUploadUtils.upload(uploadBaseDir, file);

            // 保存附件信息返回前端，前端，进行拼接成一个集合，等待添加时同时去添加
            VoucherAttachment attachment = new VoucherAttachment();
            attachment.setAttachmentName(fileName);
            attachment.setAttachmentUrl(attachmentUrl); // 保存完整路
            attachment.setCreateTime(new Date());

            // 上传成功
            return AjaxResult.success(attachment);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }


    /**
     * 导出凭证管理列表
     * @param response
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //1.查询数据
        List<VoucherExcelVO> voucherList = voucherManageService.getExcelData();

        if (voucherList == null || voucherList.isEmpty()) {
            return;
        }

        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("凭证数据", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 3. 创建 ExcelWriter（注意不要关闭流）
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

        // 4. 导出主表数据
        WriteSheet mainSheet = EasyExcel.writerSheet(0, "凭证数据")
                .head(VoucherExcelVO.class)
                .build();
        excelWriter.write(voucherList, mainSheet);

        // 6. 完成并关闭
        excelWriter.finish();
    }

    /**
     * 导入凭证数据接口
     * @param file 上传的 Excel 文件
     * @return 导入结果
     */
    @PostMapping("/importSimple")
    public AjaxResult importExcelSimple(@RequestParam("file") MultipartFile file) {
        try {
            // 使用 EasyExcel.read 创建 ExcelReaderBuilder
            List<VoucherExcelVO> voucherExcelList = EasyExcel.read(file.getInputStream())
                    .head(VoucherExcelVO.class)
                    .sheet()
                    .doReadSync();

            // 调用服务层逻辑保存数据
            if (voucherExcelList == null && voucherExcelList.isEmpty()) {
                return AjaxResult.error("数据导入失败，请检查文件格式");
            }

            voucherManageService.addVoucherAndDetail(voucherExcelList);

            return AjaxResult.success("数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("数据导入失败，请检查文件格式");
        }
    }


    /**
     * 新增凭证管理
     * @param voucherDto
     * @return
     */
    @PostMapping("/addVouchers")
    public AjaxResult addVoucherDetails(@RequestBody @Validated VoucherDto voucherDto)
    {
        return toAjax(voucherManageService.addVouchers(voucherDto));
    }



    /**
     * 查询凭证列表
     * @param voucherReqDto
     * @return
     */
    @GetMapping("/getVoucherList")
    public AjaxResult getVoucherList(VoucherReqDto voucherReqDto)
    {
        return success(voucherManageService.getVoucherList(voucherReqDto));
    }


    /**
     * 审核
     *
     * @param voucherId
     * @return
     */
    @PostMapping("/auditStatus/{voucherId}")
    public AjaxResult auditStatus(@PathVariable("voucherId") Long voucherId)
    {
        return toAjax(voucherManageService.auditStatus(voucherId));
    }


    /**
     * 反审核
     *
     * @param voucherId
     * @return
     */
    @PostMapping("/reverseAuditStatus/{voucherId}")
    public AjaxResult reverseAuditStatus(@PathVariable("voucherId") Long voucherId)
    {
        return toAjax(voucherManageService.reverseAuditStatus(voucherId));
    }


    /**
     * 红冲
     * @param voucherId
     * @return
     */
    @PostMapping("/blushVoucher/{voucherId}")
    public AjaxResult blushVoucher(@PathVariable("voucherId") Long voucherId)
    {
        return toAjax(voucherManageService.blushVoucher(voucherId));
    }


    /**
     * 作废功能
     * @param voucherId
     * @return
     */
    @PostMapping("/cancellationVoucher/{voucherId}")
    public AjaxResult cancellationVoucher(@PathVariable("voucherId") Long voucherId)
    {
        return toAjax(voucherManageService.cancellationVoucher(voucherId));
    }




    /**
     * 查询凭证管理列表
     */
    @RequiresPermissions("voucher:voucher_manage:list")
    @GetMapping("/list")
    public TableDataInfo list(VoucherManage voucherManage)
    {
        startPage();
        List<VoucherManage> list = voucherManageService.selectvoucherManageList(voucherManage);
        return getDataTable(list);
    }

    /**
     * 导出凭证管理列表
     */
    @RequiresPermissions("voucher:voucher_manage:export")
    @Log(title = "凭证管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VoucherManage voucherManage)
    {
        List<VoucherManage> list = voucherManageService.selectvoucherManageList(voucherManage);
        ExcelUtil<VoucherManage> util = new ExcelUtil<VoucherManage>(VoucherManage.class);
        util.exportExcel(response, list, "凭证管理数据");
    }

    /**
     * 获取凭证管理详细信息
     */
    @RequiresPermissions("voucher:voucher_manage:query")
    @GetMapping(value = "/{voucherId}")
    public AjaxResult getInfo(@PathVariable("voucherId") Long voucherId)
    {
        return success(voucherManageService.selectvoucherManageByVoucherId(voucherId));
    }

    /**
     * 新增凭证管理
     */
    @RequiresPermissions("voucher:voucher_manage:add")
    @Log(title = "凭证管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VoucherManage voucherManage)
    {
        return toAjax(voucherManageService.insertvoucherManage(voucherManage));
    }

    /**
     * 修改凭证管理
     */
    @RequiresPermissions("voucher:voucher_manage:edit")
    @Log(title = "凭证管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VoucherManage voucherManage)
    {
        return toAjax(voucherManageService.updatevoucherManage(voucherManage));
    }

    /**
     * 删除凭证管理
     */
    @RequiresPermissions("voucher:voucher_manage:remove")
    @Log(title = "凭证管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{voucherIds}")
    public AjaxResult remove(@PathVariable Long[] voucherIds)
    {
        return toAjax(voucherManageService.deletevoucherManageByVoucherIds(voucherIds));
    }
}
